import { getSetting, getPageSetting } from '@/services';
import { IPageSettingDetail, ISettingDetail } from '@/types';
import { addLocale, Effect, Reducer } from 'umi';

export interface SettingModelState {
  setting: Partial<ISettingDetail>;
  pageSetting: IPageSettingDetail[];
  pageLength: number;
}

export interface SettingModelType {
  namespace: 'setting';
  state: SettingModelState;
  effects: {
    getSetting: Effect;
    getPageSetting: Effect;
  };
  reducers: {
    save: Reducer<SettingModelState>;
  };
}

const SettingModel: SettingModelType = {
  namespace: 'setting',

  state: {
    setting: {},
    pageSetting: [],
    pageLength: 0
  },

  effects: {
    *getSetting({ payload }, { call, put }) {
      let result = yield call(getSetting);
      if (result.data){
          // 动态增加多语言
          if (result.data.i18n){
            const i18nLocales = JSON.parse(result.data.i18n);
            for (let locale in i18nLocales){
              addLocale(locale, i18nLocales[locale], {momentLocale: locale, antd: locale});
            }
          }
        yield put({
          type: 'save',
          payload: {
            setting: result.data
          }
        })
      }
    },
    *getPageSetting({ payload }, { call, put }) {
      let result = yield call(getPageSetting);
      if (result.data) {
        yield put({
          type: 'save',
          payload: {
            pageSetting: result.data[0],
            pageLength: result.data[1]
          }
        })
      }
    }
  },

  reducers: {
    save(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },
  }
};

export default SettingModel;